/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.nuanshui.heatedloan.search.facade.model;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.client.transport.TransportClient.Builder;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.nuanshui.framework.springContext.SpringContextUtil;

/**
 *
 * @author Uttesh Kumar T.H.
 */
public class ElasticSearchUtil {

	private static final Logger logger = LoggerFactory.getLogger(ElasticSearchUtil.class);

    private static TransportClient transportClient;

    public static synchronized TransportClient getTransportClient(ElasticSearchConfig config) throws UnknownHostException {
        try {
            if(transportClient == null) {
            	Builder builder = new Builder();
            	 transportClient =builder.build().
                         addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(config.getServerHost()), config.getIndexPort()));
            }          
            return transportClient;
        } catch (Exception e) {
            logger.error("getTransportClient", e);
        }
        return null;
    }

    public static Client getClient() {
        try {

            if(transportClient != null)
            {
                return transportClient;
            }
            ElasticSearchConfig config= SpringContextUtil.getBean(ElasticSearchConfig.class);

            return getTransportClient(config);
        } catch (Exception e) {
            logger.error("getClient", e);
        }
        return null;
    }

    public List<SearchResponse> getAllMultiResponseHits(MultiSearchResponse MultiSearchResponse) {
        try {
            List<SearchResponse> result = new ArrayList<SearchResponse>();
            for (MultiSearchResponse.Item item : MultiSearchResponse.getResponses()) {
                SearchResponse response = item.getResponse();
                result.add(response);
            }
            return result;
        } catch (Exception e) {
            logger.error("", e);
        }
        return null;
    }
}
